//
//  MNDPlusTenderDetailViewController.m
//  minidai
//
//  Created by Vitas on 2018/7/12.
//  Copyright © 2018年 迷你贷. All rights reserved.
//

#import "MNDPlusTenderDetailViewController.h"
#import "MNDPlusInputMoneyCell.h"
#import "MNDPlusRechargeCell.h"
#import "MNDPlusUseAwardTableViewCell.h"
#import <TTTAttributedLabel/TTTAttributedLabel.h>
#import "MNDWebViewController.h"
#import "MNDPulsInvestSuccessViewController.h"
#import "MNDInvestFailedViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDDepositAlertViewController.h"
#import "MNDOpenDeposAlertViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDRiskAssessWebViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDUserModel.h"
#import "MNDRechargeViewController.h"
#import "UIImage+JKColor.h"
#import "MNDConfirmInvestAlertViewController.h"
#import <IQKeyboardManager.h>
#import "MNDOpenTermsAuthViewController.h"


#define kMNDPlusInputMoneyCell @"MNDPlusInputMoneyCell"
#define kMNDPlusRechargeCell @"MNDPlusRechargeCell"
#define kMNDPlusUseAwardTableViewCell @"MNDPlusUseAwardTableViewCell"


@interface MNDPlusTenderDetailViewController ()<UITableViewDataSource,UITableViewDelegate,TTTAttributedLabelDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *investButton;
@property (weak, nonatomic) IBOutlet UIView *topContentView;
//协议label
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *protocolLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
//年利率
@property (weak, nonatomic) IBOutlet UILabel *yearAprLabel;
//期限
@property (weak, nonatomic) IBOutlet UILabel *deadlineLabel;
//显示加息
@property (weak, nonatomic) IBOutlet UILabel *aprLabel;
//显示标志
@property (weak, nonatomic) IBOutlet UILabel *limitAprLabel;

//加入时间
@property (weak, nonatomic) IBOutlet UILabel *joinTimeLabel;
//开始时间
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
//结束时间
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;

//出借金额输入框
@property(nonatomic, strong) UITextField *inputMoneyTextField;
//利息
@property (weak, nonatomic) IBOutlet UILabel *proEarnMoneyLabel;


@property (nonatomic, copy) NSString *userPhone;
@property (nonatomic, strong) MNDUserModel *userModel;
@property(nonatomic, strong) NSString *moneyStr;

//记录充值按钮
@property(nonatomic, strong) UIButton *rechargeButton;

@end

@implementation MNDPlusTenderDetailViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollNotificationAction:) name:@"scroll_up_or_down" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(investActionNotification:) name:@"bottomInvestClickNotification" object:nil];
    
    
    
    // Do any additional setup after loading the view.
}

- (void)investActionNotification:(NSNotification *)notification {
    [self goInvest];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [IQKeyboardManager sharedManager].enable = NO;
    
    if ([MNDLoginUserModel isUserLogin]) {
        
        [self loadUserInfo];
        
        [self loadUserPhone];
    }
    
}

//-(void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
//    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
//    self.navigationController.navigationBar.shadowImage = image;
//    
//    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
//    
//    
//}

- (void)setInvestModel:(MNDPlusInvestModel *)investModel {
    _investModel = investModel;
    [self configContents];
}

- (void)configContents {
    self.yearAprLabel.text = self.investModel.plan_year_apr;
    if (self.investModel.plan_coupon_apr.floatValue > 0) {
        self.aprLabel.hidden = NO;
        self.limitAprLabel.hidden = NO;
        self.aprLabel.text = [NSString stringWithFormat:@"+%@%%",self.investModel.plan_coupon_apr];
    }else {
        self.aprLabel.hidden = YES;
        self.limitAprLabel.hidden = YES;
    }
    self.deadlineLabel.text = [NSString stringWithFormat:@"封闭期%zd个月",self.investModel.plan_deadline];
    self.joinTimeLabel.text = self.investModel.join_date;
    self.startTimeLabel.text = self.investModel.start_date;
    self.endTimeLabel.text = self.investModel.end_date;
    self.moneyStr = [self.investModel.amount_available stringByReplacingOccurrencesOfString:@"," withString:@""];
    [self.tableView reloadData];
}

-(void)scrollNotificationAction:(NSNotification *)notification {
    NSInteger scrollType = [notification.object integerValue];
    if (scrollType == 1) {
        self.bottomView.backgroundColor = [UIColor whiteColor];
        self.investButton.hidden = YES;
    }else {
        self.bottomView.backgroundColor = [UIColor colorWithRGB:0xEFEFF5];
        self.investButton.hidden = NO;
    }
    
}


- (void)setupUI {
    
    self.topContentView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.topContentView.layer.shadowOpacity = 0.1;
    self.topContentView.layer.shadowOffset = CGSizeMake(2, 6);
    
    self.limitAprLabel.layer.cornerRadius = 2.0f;
    self.limitAprLabel.layer.borderColor = [UIColor whiteColor].CGColor;
    self.limitAprLabel.layer.borderWidth = 1.0f;
    
    //设置高亮颜色
    self.protocolLabel.highlightedTextColor = kColorOrange;
    //检测类型
    self.protocolLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    self.protocolLabel.delegate = self;
    //不显示下划线
    self.protocolLabel.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    NSString *text1 = @"出借即表示同意《自助投授权委托书》《借款协议》";
    [self.protocolLabel setText:text1 afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange linkRange1 = [[mutableAttributedString string] rangeOfString:@"《自助投授权委托书》" options:NSCaseInsensitiveSearch];
        NSRange linkRange3 = [[mutableAttributedString string] rangeOfString:@"《借款协议》" options:NSCaseInsensitiveSearch];
        
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorOrange} range:linkRange1];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorOrange} range:linkRange3];
        
        return mutableAttributedString;
    }];
    NSRange linkRange1 = [text1 rangeOfString:@"《自助投授权委托书》" options:NSCaseInsensitiveSearch];
    NSURL *url1 = [NSURL URLWithString:[API_BASE_URL stringByAppendingString:kAutoProtocol]];
    NSRange linkRange3 = [text1 rangeOfString:@"《借款协议》" options:NSCaseInsensitiveSearch];
    NSURL *url3 = [NSURL URLWithString:[API_BASE_URL stringByAppendingString:kLoanAccordUrl]];;
    [self.protocolLabel addLinkToURL:url1 withRange:linkRange1];
    [self.protocolLabel addLinkToURL:url3 withRange:linkRange3];
    
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = url.absoluteString;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;
    if ([url.absoluteString isEqualToString: [NSString stringWithFormat:@"%@%@",API_BASE_URL,kAutoProtocol]]) {
        webVC.title = @"自助投授权委托书";
    }else {
        webVC.title = @"借款协议";
    }
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    
    [self presentViewController:navVC animated:YES completion:^{
        
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }else {
        return 1;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    kdeclare_weakself;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            MNDPlusRechargeCell *cell = [tableView dequeueReusableCellWithIdentifier:kMNDPlusRechargeCell];
            if(self.investModel.amount_available.length > 0) {
                cell.availableMoneyLabel.text = [NSString stringWithFormat:@"可用余额(元)  %@",self.investModel.amount_available];
            }
           self.rechargeButton = cell.rechargeButton;
            return cell;
            
        }else {
            
            MNDPlusInputMoneyCell *cell = [tableView dequeueReusableCellWithIdentifier:kMNDPlusInputMoneyCell];
            NSLog(@"amount_available = %@",weakSelf.investModel.amount_available);
            if (self.investModel.plan_lowest_money.length > 0) {
                cell.inputMoneyTextField.placeholder = [NSString stringWithFormat:@"%@元起",self.investModel.plan_lowest_money];
            }
            [[cell.inputMoneyTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
                if (cell.inputMoneyTextField.text.floatValue > weakSelf.moneyStr.floatValue) {
                    cell.inputMoneyTextField.text = weakSelf.moneyStr;
                }
                if (cell.inputMoneyTextField.text.floatValue > weakSelf.investModel.plan_most_money.floatValue) {
                    cell.inputMoneyTextField.text = weakSelf.investModel.plan_most_money;
                }
                //计算利息
                [weakSelf calculatedInterest];
            }];
            cell.inputMoneyTextField.tag = 100;
            cell.inputMoneyTextField.delegate = self;
            self.inputMoneyTextField = cell.inputMoneyTextField;
            
            [cell.allInvestButton bk_addEventHandler:^(id sender) {
                NSString *amountStr = [weakSelf.investModel.amount_available stringByReplacingOccurrencesOfString:@"," withString:@""];
                if ( amountStr.floatValue >= weakSelf.investModel.plan_most_money.floatValue) {
                    weakSelf.inputMoneyTextField.text = weakSelf.investModel.plan_most_money;
                }else {
                    weakSelf.inputMoneyTextField.text = amountStr;
                }
                //计算利息
                [weakSelf calculatedInterest];
            } forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    }else {
        MNDPlusUseAwardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kMNDPlusUseAwardTableViewCell];
        return cell;
    }
}

- (void)calculatedInterest {
    //可投资金额
    
    CGFloat yearApr = self.investModel.plan_year_apr.floatValue + self.investModel.plan_coupon_apr.floatValue;

    CGFloat daedline = self.investModel.plan_deadline;
    float num = self.inputMoneyTextField.text.floatValue;
    //计算利益
    float money = num*yearApr*daedline/12/100*0.95;
    money = round(money*100)/100;
    self.proEarnMoneyLabel.text = [NSString stringWithFormat:@"%.2f元",money];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            return 55;
        }else {
            return 55;
        }
    }else {
        return 55;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat presentHeight = scrollView.contentOffset.y - (scrollView.contentSize.height - screenHeight);
    NSLog(@"-----%f-----",scrollView.contentOffset.y);
    NSLog(@"velocity = %f",velocity.y);
    //大于60，向上滚动
    if (velocity.y >0) {
        if (presentHeight >= 140) {
            self.investButton.hidden = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [scrollView setContentOffset:CGPointMake(0, 0)];
            });
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@1];
        }
    }
}


- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if (textField.tag == 100) {
        self.rechargeButton.userInteractionEnabled = NO;
        self.tableView.scrollEnabled = NO;
        [self.tableView setContentOffset:CGPointMake(0, 60)];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@0];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if (textField.tag == 100) {
        self.rechargeButton.userInteractionEnabled = YES;
        self.tableView.scrollEnabled = YES;
        [self.tableView setContentOffset:CGPointMake(0, 0)];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@0];
    }
}
//设置textfield输入内容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 100) {
        NSScanner      *scanner    = [NSScanner scannerWithString:string];
        NSCharacterSet *numbers;
        NSRange         pointRange = [textField.text rangeOfString:@"."];
        
        if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }
        else
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
        
        if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
        {
            return NO;
        }
        
        short remain = 2; //默认保留2位小数
        
        NSString *tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
            if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
                return NO;
            }
            if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                return NO;
            }
        }
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
            if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                textField.text = string;
                return NO;
            }else{
                if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                    if([string isEqualToString:@"0"]){
                        return NO;
                    }
                }
            }
        }
        
        NSString *buffer;
        if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
        {
            return NO;
        }
    }
    
    return YES;
}

//点击充值按钮
- (IBAction)clickLackMoneyBtn:(UIButton *)sender {
    
    [self goRecharge];
}

/**
 充值
 */
- (void)goRecharge {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Recharge" bundle:nil];
    MNDRechargeViewController *rechargeVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDRechargeViewController"];
    rechargeVC.isFromTender = YES;
    rechargeVC.isShowCustomBack = YES;
    [self.navigationController pushViewController:rechargeVC animated:YES];
}


//上方出借按钮点击事件
- (IBAction)investAction:(UIButton *)sender {
    [self goInvest];
}

- (void)goInvest{
    
    if(self.inputMoneyTextField.text.length <= 0 || self.inputMoneyTextField.text.floatValue == 0) {
        [NetworkProgressHUD showHudMsg:@"请输入金额"];
        return;
    }
    
    if(self.inputMoneyTextField.text.floatValue < self.investModel.plan_lowest_money.floatValue) {
        [NetworkProgressHUD showHudMsg:@"输入金额小于最低可投金额"];
        return;
    }
    kdeclare_weakself;
    __weak MNDConfirmInvestAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:@"MNDConfirmInvestAlertViewController"];
    alertVC.moneyStr = self.inputMoneyTextField.text;
    alertVC.amountStr = self.investModel.amount_available;
    __weak UIView *springView = alertVC.view;
    [self.view addSubview:springView];
    [self addChildViewController:alertVC];
    //    __weak typeof(self) weakSelf = self;
    [alertVC.closeButton bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
            
        }];
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.confirmButton bk_addEventHandler:^(id sender) {
        [weakSelf requestInvestData];
    } forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)requestInvestData{
    
    [NetworkProgressHUD showHud];
    kdeclare_weakself;
    //请求投资
    NSString *investMoney = self.inputMoneyTextField.text;
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"plan_id":@(self.investModel.plan_id),@"sign_money":investMoney}];
    
    [APIManager sendRequestWithPath:API_AUTO_PLUS_INVEST parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        [NetworkProgressHUD hideHud];
        
        if (responseModel.status == ResponseSuccess) {
            
            MNDPulsInvestSuccessViewController *investSucessVC = [UIStoryboard viewControllerWithIdentifier:@"MNDPulsInvestSuccessViewController"];
            investSucessVC.investMoneyStr = self.inputMoneyTextField.text;
            investSucessVC.proEarnMoneyStr = self.proEarnMoneyLabel.text;
            investSucessVC.sign_id = responseModel.data[@"sign_id"];
            investSucessVC.plusTitle = self.investModel.plan_title;
            [weakSelf.navigationController pushViewController:investSucessVC animated:YES];
        } else {
            NSDictionary *msgDict = responseModel.msg;
            if ([msgDict.allKeys containsObject:@"sign"]) {
                if ([responseModel.msg[@"sign"] isEqualToString:kOpenAccount] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSetPassword] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignPayment] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignAutoTender] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignAutoTransfer] ||
                    [responseModel.msg[@"sign"] isEqualToString:kRiskEvaluation] ||
                    [responseModel.msg[@"sign"] isEqualToString:kBandcard] ||
                    [responseModel.msg[@"sign"] isEqualToString:kExpiredSignPayment] ||
                    [responseModel.msg[@"sign"] isEqualToString:kExpiredAutotender]
                    ) {
                    [weakSelf showDepositAlertWithModel:responseModel];
                }else if([responseModel.msg[@"sign"] isEqualToString:@"tender_money"]) {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                }else {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                    //                    MNDInvestFailedViewController *failedVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestFailedViewController"];
                    //                    [weakSelf.navigationController pushViewController:failedVC animated:YES];
                }
                
            } else {
                MNDInvestFailedViewController *failedVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestFailedViewController"];
                [weakSelf.navigationController pushViewController:failedVC animated:YES];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)showDepositAlertWithModel:(ResponseModel *)response {
    NSString *signStr = response.msg[@"sign"];
    
    
    
    //开通存管账户
    if ([signStr isEqualToString:kOpenAccount]) {
        
        [self showOpenAccountAlertWithModel:response];
        return;
    }
    
    //风险等级未评测
    if ([signStr isEqualToString:kRiskEvaluation]) {
        
        [self showRiskAlertView];
        return;
    }
    
//    if ([signStr isEqualToString:@"set_password"]) {
        __weak MNDOpenDeposAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDeposAlertViewController description]];
        
        __weak UIView *alertView = alertVC.view;
        [KeyWindow addSubview:alertView];
        [self.tabBarController addChildViewController:alertVC];
        
        WeakSelf(self);
        
        [alertVC.confirmButton bk_addEventHandler:^(id sender) {
            [alertView removeFromSuperview];
            [alertVC removeFromParentViewController];
            
            [weakself toOpenDepositoryWithModel:response];
            
        } forControlEvents:UIControlEventTouchUpInside];
        
        alertVC.alertMessage = response.msg[@"error"];
        alertVC.alertType = response.msg[@"sign"];
//    }
    
}

- (void)showOpenAccountAlertWithModel:(ResponseModel *)response {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDDepositAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDDepositAlertViewController description]];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self.tabBarController addChildViewController:alertVC];
    
    __weak typeof(self) weakSelf = self;
    
    [alertVC.depositBtn bk_addEventHandler:^(id sender) {
        [springView removeFromSuperview];
        [alertVC removeFromParentViewController];
        [weakSelf toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.closeBtn bk_addEventHandler:^(id sender) {
        
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainerView.frame = CGRectMake(alertVC.alertContainerView.frame.origin.x, kScreenHeight, alertVC.alertContainerView.frame.size.width, alertVC.alertContainerView.frame.size.height);
            alertVC.closeBtn.frame = CGRectMake(alertVC.closeBtn.frame.origin.x, kScreenHeight, alertVC.closeBtn.frame.size.width, alertVC.closeBtn.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)toOpenDepositoryWithModel:(ResponseModel *)response {
    NSLog(@"self: %@", self);
    NSLog(@"viewcontrollers: %@", self.navigationController.viewControllers);
    NSInteger index = [self.navigationController.viewControllers indexOfObject:self.navigationController.topViewController];
    
    NSLog(@"index: %zd", index);
    
    NSString *signStr = response.msg[@"sign"];
    //开通存管
    if ([signStr isEqualToString:kOpenAccount]) {
        MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
        realVC.fromNaviIndex = index;
        
        [self.navigationController pushViewController:realVC animated:YES];
        
        return;
    }
    //设置交易密码
    if ([signStr isEqualToString:kSetPassword]) {
        
        [self loadPaymentPassword];
        return;
    }
    //授权三和一
    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment] || [signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender] || [signStr isEqualToString:kSignAutoTransfer]) {
        MNDOpenTermsAuthViewController *openTermsAuthVC = [UIStoryboard viewControllerWithIdentifier:@"MNDOpenTermsAuthViewController"];
        openTermsAuthVC.fromNaviIndex = index;
        [self.navigationController pushViewController:openTermsAuthVC animated:YES];
        return;
    }
//    //设置缴费授权
//    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment]) {
//        
//        MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
//        paymentVC.fromNaviIndex = index;
//        
//        [self.navigationController pushViewController:paymentVC animated:YES];
//        
//        return;
//    }
//    //设置自动投标
//    if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
//        
//        MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
//        tenderVC.isResign = [signStr isEqualToString:kExpiredAutotender];
//        if (self.userPhone.length > 0) {
//            tenderVC.fromNaviIndex = index;
//            tenderVC.phoneNumber = self.userPhone;
//            
//            [self.navigationController pushViewController:tenderVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
//    //设置自动债转
//    if ([signStr isEqualToString:kSignAutoTransfer]) {
//        
//        MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
//        if (self.userPhone.length > 0) {
//            transferVC.fromNaviIndex = index;
//            transferVC.phoneNumber = self.userPhone;
//            
//            [self.navigationController pushViewController:transferVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
    
    //风险等级未评测
    if ([signStr isEqualToString:kRiskEvaluation]) {
        
        [self showRiskAlertView];
        return;
    }
}

- (void)showRiskAlertView {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有完成[出借用户风险等级测评]，根据金融监管政策要求，用户需要先完成评估才能出借。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"去测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSInteger index = [self.navigationController.viewControllers indexOfObject:self.navigationController.topViewController];
        
        MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
        riskVC.webViewUrl = self.userModel.evaluationUrl;
        riskVC.indexOfViewController = index;
        riskVC.title = @"风险测评";
        [self.navigationController pushViewController:riskVC animated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

/**
 获取存管手机号
 */
- (void)loadUserPhone {
    
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParam];
    [APIManager sendRequestWithPath:API_DEPOSIT_GET_PHONE parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.userPhone = responseModel.data;
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadUserInfo {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
            
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"设置交易密码";
            NSLog(@"viewcontrollers: %@", weakself.navigationController.viewControllers);
            NSInteger index = [weakself.navigationController.viewControllers indexOfObject:self.navigationController.topViewController];
            webVC.fromNaviIndex = index;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
